<?php

namespace backend\models\service;

use Yii;
use yii\data\Sort;
use backend\models\odm\AdminOdm as Admin;

class AdminService extends Admin {

    private $_query;
    private $_sn;
    public $password_repeat;
    public $password_new;
    private static $_items = [];

    /**
     * @inheritdocpublic 
     */
    public function rules() {
        return [
            [['password_hash', 'username'], 'required', 'message' => '{attribute}不能为空'],
            [['password_hash'], 'string', 'max' => 30, 'min' => 6, 'tooShort' => '{attribute}太短了', 'tooLong' => '{attribute}太长了'],
            [['password_repeat'], 'compare', 'compareAttribute' => 'password_hash', 'message' => '两次密码不一致'],
            ['admin_sn', 'validateAdminSn'],
        ];
    }

    public function init() {
        parent::init();
        $this->_query = static::find();
    }


    /**
     * @inheritdoc
     */
    public function attributeLabels() {
        return [
            'password_hash' => '密码',
            'password_repeat' => '确认密码',
        ];
    }

    public static function setPassword($password) {
        $password_hash = Yii::$app->security->generatePasswordHash($password);
        return $password_hash;
    }

    /**
     *
     * @return User|null
     */
    protected function getAdmin() {
        if ($this->_sn === null) {
            $this->_sn = Admin::findOne(['admin_sn' => $this->admin_sn]);
//            $commandQuery = clone $this->_sn;
//
//            echo $commandQuery->createCommand()->getRawSql();
//            exit;
        }
        return $this->_sn;
    }

    public function validateAdminSn($attribute, $params) {
        if (!$this->hasErrors()) {
            $admin = $this->getAdmin();
            if ($admin) {
                $this->addError($attribute, '该账号已存在.');
            }
        }
    }

    public function search() {
        $query = Admin::find();
        $query->andFilterWhere([
            'id' => $this->id,
        ]);

        return $query;
    }

    /**
     * Creates data provider instance with search query applied
     *
     * @param array $params
     *
     * @return ActiveDataProvider
     */
    public function getQuerySearch($params) {
        $this->load($params);
        $this->_query->andFilterWhere([
            'id' => $this->id,
        ]);

        return $this;
    }

    /**
     * 排序/分页
     * 
     * @return []
     */
    public function getQueryDataprovider() {
        $sort = new Sort([
            'defaultOrder' => ['create_time' => SORT_DESC],
            'attributes' => [
                'create_time',
            ],
        ]);
        $this->_query->orderBy($sort->orders);

        $dataProvider = new ActiveDataProvider([
            'query' => $this->_query,
            'sort' => $sort,
            'pagination' => [
                'pagesize' => 10,
            ]
        ]);

        $data = [];
        if (!empty($dataProvider->models))
            foreach ($dataProvider->models as $key => $model) {
                $date = date("Y.m.d", $model->create_time);
                $data[$date][] = $model;
            }
        return ['dataProvider' => $dataProvider, 'data' => $data];
    }

    public static function items($type) {
        if (!isset(self::$_items[$type])) {
            self::loadItems($type);
        }
        return self::$_items[$type];
    }

    private static function loadItems($type) {
        self::$_items[$type] = [];
        $models = static::find()->where(['type' => $type])->orderBy(['id' => SORT_ASC])->asArray()->all();
        foreach ($models as $model) {
            self::$_items[$type][$model['id']] = $model['username'];
        }
    }

    public static function getChannelNums($pid, $type) {
        $sql = 'select count(*) as n from xs_admin where pid = ' . $pid . ' and type = ' . $type;
        $res = Yii::$app->db->createCommand($sql)->queryOne();

        return $res['n'];
    }

    public static function getChannelList($pid, $type) {
        $sql = 'select username,id from xs_admin where pid = ' . $pid . ' and type = ' . $type;
        $res = Yii::$app->db->createCommand($sql)->queryAll();
        return $res;
    }
    
    
    public static function getInfoDatas($id) {
        $sql = 'select username,id from xs_admin where id = ' . $id ;
        $res = Yii::$app->db->createCommand($sql)->queryOne();
        return $res;
    }
    
     public function getAdminByUsername($username){
        $sql = "select * from xs_admin where username = '$username'";
        $info = Yii::$app->db->createCommand($sql)->queryOne();
        return $info;
    }

}
